import pdb
import logging
import shutil
import uuid

from celery import shared_task
from dotenv import load_dotenv

from system.ui_test_case.schema import UiCaseStepIn

load_dotenv()
import os
import glob
import asyncio
import argparse
import os

logger = logging.getLogger(__name__)

from celery_app import  celery_app

from browser_use.agent.service import Agent
from playwright.async_api import async_playwright
from browser_use.browser.browser import Browser, BrowserConfig
from browser_use.browser.context import (
    BrowserContextConfig,
    BrowserContextWindowSize,
)
from langchain_ollama import ChatOllama
from playwright.async_api import async_playwright
from browser_ai.utils.agent_state import AgentState

from browser_ai.utils import utils
from browser_ai.agent.custom_agent import CustomAgent
from browser_ai.browser.custom_browser import CustomBrowser
from browser_ai.agent.custom_prompts import CustomSystemPrompt, CustomAgentMessagePrompt
from browser_ai.browser.custom_context import BrowserContextConfig, CustomBrowserContext
from browser_ai.controller.custom_controller import CustomController
from config import  BASE_DIR ,STATIC_URL,DEBUG_VIDEO_URL
# 全局字典记录任务的唯一标识及其状态
task_status = {}


async def execute_ui_task(task_id: str,uiCaseStepIn:list[UiCaseStepIn],filePath:str):
    # 检查任务是否已经执行过
    if task_id in task_status and task_status[task_id] == "running":
        logger.info(f"任务 {task_id} 已经在执行中，跳过重复执行。")
        return

    # 标记任务为正在执行
    task_status[task_id] = "running"
    logger.info(f"任务 {task_id} 开始执行...")

    # 设置任务参数
    llm_provider = 'deepseek'
    llm_model_name = 'deepseek-ai/DeepSeek-V3'
    llm_temperature = 0
    llm_base_url = 'https://api.siliconflow.cn/v1'
    llm_api_key = 'sk-vdzmowztyelagwjybuovvrralojysncrgalsrivvksllakdl'
    use_own_browser = False
    keep_browser_open = False
    headless = False
    disable_security = True
    save_recording_path = os.path.join(BASE_DIR ,STATIC_URL,DEBUG_VIDEO_URL)

    save_trace_path = None
    # enable_recording = True
    add_infos = ''
    max_steps = 100
    use_vision = False
    max_actions_per_step = 1
    tool_calling_method = None
    controller = CustomController()

    # 获取 LLM 模型
    llm = utils.get_llm_model(
        provider=llm_provider,
        model_name=llm_model_name,
        temperature=llm_temperature,
        base_url=llm_base_url,
        api_key=llm_api_key,
    )

    # 初始化浏览器
    browser = Browser(
        config=BrowserConfig(
            headless=headless,
            disable_security=disable_security,
        )
    )

    # 创建浏览器上下文
    browser_context = await browser.new_context(
        config=BrowserContextConfig(
            trace_path=save_trace_path if save_trace_path else None,
            save_recording_path=save_recording_path if save_recording_path else None,
            no_viewport=False,
            browser_window_size=BrowserContextWindowSize(width=1980, height=700),
        )
    )

    # 创建 CustomAgent 实例
    agent = CustomAgent(
        task=uiCaseStepIn[0]['stepDescription'],
        add_infos=add_infos,
        use_vision=use_vision,
        llm=llm,
        browser=browser,
        controller=controller,
        browser_context=browser_context,
        system_prompt_class=CustomSystemPrompt,
        agent_prompt_class=CustomAgentMessagePrompt,
        max_actions_per_step=max_actions_per_step,
        agent_state={},
        tool_calling_method=tool_calling_method,
        save_response_file=filePath
    )

    # 执行任务
    try:
        result = await agent.run(max_steps=max_steps)
        page = await browser_context.get_current_page()
        path = await  page.video.path()
        print(path)
        shutil.copy(path, os.path.join(BASE_DIR ,STATIC_URL,DEBUG_VIDEO_URL,task_id+'.webm'))
    except Exception as e:
        logger.info(f"任务 {task_id} 执行时出错: {e}")
    finally:
        await browser.close()
        await browser_context.close()
        if path is not None:
            file_exists = os.path.exists(path)
        # 如果文件存在，删除它
            if file_exists:
                logger.info(f"文件 {file_exists} 存在，正在删除...")
                os.remove(path)
    # 标记任务为已完成
        logging.info(f"任务 {task_id} 已完成。")

@shared_task
def do_execute_ui_task(task_id:str,uiCaseStepIn:list[UiCaseStepIn],filePath:str):
    return asyncio.run(execute_ui_task(task_id,uiCaseStepIn,filePath))






